package com.diandi.activity.manager.impl;

import com.diandi.activity.bean.Activity;
import com.diandi.activity.bean.ActivityRule;
import com.diandi.activity.bean.LotteryTicket;
import com.diandi.activity.bean.RewardPointType;
import com.diandi.activity.manager.ActivityManager;
import com.diandi.activity.mapper.ActivityMapper;
import com.diandi.activity.mapper.CenterLotteryTicketMapper;
import com.diandi.ddsb.bean.*;
import com.diandi.ddsb.mapper.ActivityOldMapper;
import com.diandi.ddsb.vo.*;
import com.diandi.utils.DateUtil;
import com.diandi.utils.NumberUtil;
import com.diandi.utils.ServiceException;
import com.diandi.utils.YesOrNoType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * Created by a on 2018/3/20.
 */
@Component
public class ActivityManagerImpl implements ActivityManager {
    private static Logger logger = LoggerFactory.getLogger(ActivityManagerImpl.class);

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityOldMapper activityOldMapper;
    @Autowired
    private CenterLotteryTicketMapper centerLotteryTicketMapper;

    @Override
    public List<Activity> queryActivitys(Map<String, Object> paramMap) {
        return activityMapper.queryActivitys(paramMap);
    }

    @Override
    public Integer queryActivitysCount(Map paramMap) {
        return activityMapper.queryActivitysCount(paramMap);
    }

    @Override
    public Results addNewInvestActivity(NewActivityInfoVo activityInfoVo) {
        Results result = new Results();
        result.setCode(Constant.SUCCESS);

        boolean flag = false;

        if (activityInfoVo.getRewardPoint() == RewardPointType.invitation.getValue()
                || activityInfoVo.getRewardPoint() == RewardPointType.NEW_INVITATION_ACTIVITY.getValue()) {
//			if (!checkUrl(activityInfoVo.getPcLink())) {
//				throw new ServiceException("请输入正确的PCLINK");
//			}
//			if (!checkUrl(activityInfoVo.getH5Link())) {
//				throw new ServiceException("请输入正确的H5LINK");
//			}
//			if (!checkUrl(activityInfoVo.getIosLink())) {
//				throw new ServiceException("请输入正确的iosLINK");
//			}
//			if (!checkUrl(activityInfoVo.getAndroidLink())) {
//				throw new ServiceException("请输入正确的AndroidLINK");
//			}
            activityInfoVo.setRegisterEnd(DateUtil.getAssembleTime(activityInfoVo.getRegisterEndInvite(), " 23:59:59"));
        }
        if(activityInfoVo.getRewardPoint() == 40){//添加秒借邀请活动
            if(activityInfoVo.getRuleList().size() == 0 || activityInfoVo.getRuleList() == null || activityInfoVo.getRuleList().isEmpty()){
                logger.info("条件为空");
                throw new ServiceException("条件为空");
            }
            Map<String , Object> map = activityMapper.getMiaoJieInvestInfo();
            if(map != null && map.size() != 0){
                logger.info("当前已存在有效的秒借进行中邀请活动");
                throw new ServiceException("当前已存在有效的秒借进行中邀请活动");
            }
        }
        if (null == activityInfoVo.getRuleList() || activityInfoVo.getRuleList().isEmpty()) {
            throw new ServiceException("请添加规则!");
        }

        List<String> ticketIds = new ArrayList<String>();
        List<ActivityRule> ruleList_ = activityInfoVo.getRuleList();
        List<ActivityRule> ruleList = new ArrayList<ActivityRule>();
        for (ActivityRule rule : ruleList_) {
            if (rule.getStatus() == YesOrNoType.YES.getValue()) {
                ruleList.add(rule);
            }
        }
        activityInfoVo.setRuleList(ruleList);

        for (ActivityRule rule : ruleList) {
            ticketIds.add(rule.getTicketId() + "");
        }

        List<LotteryTicket> tickets = activityMapper.getNotUsedTicketByIds(ticketIds);
        if (null != tickets && 0 != tickets.size()) {
            for (LotteryTicket ticket : tickets) {
                if (ticket.getActivityId() != null) {
                    throw new ServiceException("奖池{" + ticket.getId() + "}已经被使用，请选择其他奖池！");
                }
                if (ticket.getEndTime().getTime() < activityInfoVo.getRegisterEnd().getTime()) {
                    throw new ServiceException("奖池:{" + ticket.getId() + "}的结束时间不得小于活动的结束时间!");
                }
				/*
				 * if (ticket.getType() ==
				 * LotteryTicketType.CASH_PACKAGE.getValue() && tickets.size() >
				 * 1) { throw new ServiceException("奖池:{" + ticket.getId() +
				 * "}属于现金红包,在活动中仅能单独存在!"); }
				 */

				/*
				 * if (ticket.getType() ==
				 * LotteryTicketType.CASH_PACKAGE.getValue()) { flag = true;//
				 * 属于投资活动，并包含现金红包会触发活动唯一校验 }
				 */
            }
        }

        if (activityInfoVo.getRewardPoint() != null
                && (activityInfoVo.getRewardPoint() == RewardPointType.REGISTER.getValue()
                || activityInfoVo.getRewardPoint() == RewardPointType.REAL_NAME_AUTH.getValue()
                || activityInfoVo.getRewardPoint() == RewardPointType.FIRST_RECHARGE.getValue()
                || activityInfoVo.getRewardPoint() == RewardPointType.FIRST_INVEST.getValue()
                || activityInfoVo.getRewardPoint() == RewardPointType.NEW_INVITATION_ACTIVITY.getValue()
                || activityInfoVo.getRewardPoint() == RewardPointType.FIRST_INVEST_24_HOURSE.getValue() || activityInfoVo
                .getRewardPoint() == RewardPointType.invitation.getValue()) && activityInfoVo.getStatus() == 1
                || (activityInfoVo.getRewardPoint() == RewardPointType.invest_send_hb.getValue() && flag)) {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("rewardPoint", activityInfoVo.getRewardPoint());
            if (activityInfoVo.getRewardPoint() != RewardPointType.invitation.getValue()
                    && activityInfoVo.getRewardPoint() != RewardPointType.invest_send_hb.getValue()) {
                paramMap.put("publishPlatforms", activityInfoVo.getPublishPlatforms());
            }
            paramMap.put("status", activityInfoVo.getStatus());
            paramMap.put("registerStartForX", activityInfoVo.getRegisterStart());
            paramMap.put("registerEndForX", activityInfoVo.getRegisterEnd());
            List<Activity> activityInfoVos = activityMapper.queryActivitys(paramMap);
            if (flag) {
                for (Activity activity : activityInfoVos) {
                    for (LotteryTicket ticket : activity.getTickets()) {
                        if (ticket.getType() == LotteryTicketType.CASH_PACKAGE.getValue()) {
                            throw new ServiceException("您当前建立的活动与ID为" + activity.getId() + "的活动发生冲突，请修改后保存！");
                        }
                    }
                }
            } else {
                if (activityInfoVos != null && activityInfoVos.size() > 0) {
                    throw new ServiceException("您当前建立的活动与ID为" + activityInfoVos.get(0).getId() + "的活动发生冲突，请修改后保存！");
                }
            }
        }

        if (activityInfoVo.getRewardPoint() == RewardPointType.invest_send_hb.getValue()
                || activityInfoVo.getRewardPoint() == RewardPointType.INVEST_ACTIVITY.getValue()) {
            if (isBlank(activityInfoVo.getBorrowTypes())) {
                throw new ServiceException("新增奖券失败:请填勾选适用标!");
            }
            if (isBlank(activityInfoVo.getPublishPlatforms())) {
                throw new ServiceException("新增奖券失败:请填勾选适用平台!");
            }
            activityInfoVo.setRegisterEnd(DateUtil.getAssembleTime(activityInfoVo.getRegisterEnd(), " 23:59:59"));
        }

        insertRuleActity(activityInfoVo, tickets);

        return result;
    }
    private void insertRuleActity(NewActivityInfoVo activityInfoVo, List<LotteryTicket> tickets) {
        String rsMsg = "";
        Long exActeRs = 0L;
        int exeRs = 0;
        Long ruleRs = 0L;
        try {



            /********************************插入老系统****************************/
            //插入老系统
            activityOldMapper.insertActivity(activityInfoVo);//返回老系统活动主键插入新系统外键

            if (tickets != null && tickets.size() > 0) {
                for (LotteryTicket lotteryTicket : tickets) {
                    Map<String , Object> map = new HashMap<String , Object>();
                    LotteryTicket l = centerLotteryTicketMapper.getLotteryTicketById(lotteryTicket.getId());
                    //查询奖池信息
                    lotteryTicket.setActivityId(activityInfoVo.getId());
                    lotteryTicket.setId(l.getOldTicketId());
                    exeRs = activityOldMapper.updateLotteryTicket(lotteryTicket);
                    LotteryTicketInfoVo ls = centerLotteryTicketMapper.getTicketByOldId(lotteryTicket.getId());
                    lotteryTicket.setId(ls.getId());
                    if (exeRs <= SystemConstant.FINAL_INT_ZERO) {
                        rsMsg += "更新券：" + lotteryTicket.getId() + "关联时失败!";
                    }
                }
            }

            List<ActivityRule> ruleList = activityInfoVo.getRuleList();

            for (ActivityRule rule : ruleList) {
                rule.setActivityId(activityInfoVo.getId());
            }

            ruleRs = activityOldMapper.batchInsertActivityRule(ruleList);

            if (ruleRs != activityInfoVo.getRuleList().size()) {
                rsMsg += "更新规则失败";
            }

            /**********************************************************************/


            //插入新系统

            // 插入数据库
            activityInfoVo.setOldActivityId(activityInfoVo.getId());
            exActeRs = activityMapper.insertActivity(activityInfoVo);




            if (exActeRs <= SystemConstant.FINAL_INT_ZERO) {
                rsMsg = "存活动失败！";
            }
            if (tickets != null && tickets.size() > 0) {
                for (LotteryTicket lotteryTicket : tickets) {
                    lotteryTicket.setActivityId(activityInfoVo.getId());
                    //根据老系统id查主键
//                    LotteryTicketInfoVo l = centerLotteryTicketMapper.getTicketByOldId(lotteryTicket.getId());
//                    lotteryTicket.setId(l.getId());
                    exeRs = activityMapper.updateLotteryTicket(lotteryTicket);
                    if (exeRs <= SystemConstant.FINAL_INT_ZERO) {
                        rsMsg += "更新券：" + lotteryTicket.getId() + "关联时失败!";
                    }
                }
            }

            ruleList = activityInfoVo.getRuleList();

            for (ActivityRule rule : ruleList) {
                rule.setActivityId(activityInfoVo.getId());
            }

            ruleRs = activityOldMapper.batchInsertActivityRule(ruleList);

            if (ruleRs != activityInfoVo.getRuleList().size()) {
                rsMsg += "更新规则失败";
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("异常：" + e.getMessage());
        }
        if (exActeRs <= SystemConstant.FINAL_INT_ZERO) {
            throw new ServiceException(rsMsg);
        }
        if (tickets != null && tickets.size() > 0) {
            if (exeRs <= SystemConstant.FINAL_INT_ZERO) {
                throw new ServiceException(rsMsg);
            }
        }

        if (ruleRs != activityInfoVo.getRuleList().size()) {
            throw new ServiceException(rsMsg);
        }
        /**********************************************************************/

    }

    @Override
    public ActivityInfoVo getActivityById(Long id) {
        ActivityInfoVo vo = activityMapper.getActivityById(id);
        if (vo.getRebateRate() != null) {
            vo.setRebateRate(NumberUtil.doubleDivide(vo.getRebateRate(), 0.01d));
        }
        return vo;
    }

    @Override
    public List<Rule> queryRuleByActivityId(Long id) {
        List<Rule> re = activityMapper.queryRuleByActivityId(id);
        return re;
    }

    @Override
    public List<PrizeVo> queryPrizeByActivityId(Long activityId) {
        return activityMapper.queryPrizeByActivityId(activityId);
    }
    @Override
    public List<ActivityRuleVo> queryActRuleByEntity(ActivityRule activityRule) {
        List<ActivityRule> ruleList = activityMapper.queryActRuleByEntity(activityRule);

        List<ActivityRuleVo> voList = new ArrayList<ActivityRuleVo>();
        if (null != ruleList && 0 != ruleList.size()) {
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            for (ActivityRule rule : ruleList) {
                ActivityRuleVo vo = new ActivityRuleVo();

                vo.setId(rule.getId());
                vo.setInvestMonth(rule.getInvestMonth());
                vo.setTicketId(rule.getTicketId());
                vo.setInvitePeopleNum(rule.getInvitePeopleNum());
                vo.setRewardPointInRule(rule.getRewardPointInRule());
                //针对分时段投资活动，将存储的时间毫秒值格式化为前端可展示文字
                if(rule.getRewardPointInRule() !=null &&rule.getRewardPointInRule()==1){
                    Integer startInt = rule.getHqbInvestDaysFrom();
                    Integer endInt = rule.getHqbInvestDaysTo();
                    //格式化时间，只保留时间部分
                    if(startInt != null){
                        Long start = 1488297600000L + startInt;
                        Date startTime = new Date(start);
                        vo.setHqbInvestDaysFromStr(sf.format(startTime));
                    }
                    if(endInt != null){
                        Long end = 1488297600000L + endInt;
                        Date endTime = new Date(end);
                        vo.setHqbInvestDaysToStr(sf.format(endTime));
                    }
                }
                LotteryTicket lotteryTicket = rule.getLoteryTicket();
                if (null != lotteryTicket) {
                    vo.setTicketTitle(lotteryTicket.getTitle());
                    vo.setTicketTypeText(null == lotteryTicket.getType() ? "" : LotteryTicketType.getTextByValue(
                            lotteryTicket.getType()).getText());
                } else {
                    vo.setTicketTitle("");
                    vo.setTicketTypeText("");
                }
                vo.setRepayAmountFrom(null == rule.getRepayAmountFrom() ? 0.0d : rule.getRepayAmountFrom());
                vo.setRepayAmountTo(null == rule.getRepayAmountTo() ? 0.0d : rule.getRepayAmountTo());
                vo.setInvestAmountFrom(rule.getInvestAmountFrom());
                vo.setInvestAmountTo(rule.getInvestAmountTo());

                if (null == rule.getHqbInvestDaysFrom() && null == rule.getHqbInvestDaysTo()) {
                    vo.setHqbInvestDaysText("无限制");
                } else if (null == rule.getHqbInvestDaysFrom()) {
                    vo.setHqbInvestDaysText("持有天数<=" + rule.getHqbInvestDaysTo() + "天");
                } else if (null == rule.getHqbInvestDaysTo()) {
                    vo.setHqbInvestDaysText("持有天数>=" + rule.getHqbInvestDaysFrom() + "天");
                } else {
                    vo.setHqbInvestDaysText(rule.getHqbInvestDaysFrom() + "天<=持有天数<=" + rule.getHqbInvestDaysTo() + "天");
                }

                if (null == rule.getInvestAmountFrom() && null == rule.getInvestAmountTo()) {
                    vo.setInvestAmountText("-----");
                } else if (null == rule.getInvestAmountFrom()) {
                    vo.setInvestAmountText("----" + rule.getInvestAmountTo());
                } else if (null == rule.getInvestAmountTo()) {
                    vo.setInvestAmountText(rule.getInvestAmountFrom() + "----");
                } else {
                    vo.setInvestAmountText(rule.getInvestAmountFrom() + "---" + rule.getInvestAmountTo());
                }

                if (null != rule.getInvestAmountCheckType()) {
                    vo.setInvestAmountCheckType(InvestAmountCheckType.getTextByValue(rule.getInvestAmountCheckType())
                            .getText());

                    if (InvestAmountCheckType.ACCORDING_INVEST_AMOUNT.getValue() == rule.getInvestAmountCheckType()) {
                        vo.setInvestAmountText(rule.getInvestAmountDivisor() + "元");
                    }
                }
//				vo.setRepayAmountFrom(null == rule.getRepayAmountFrom() ? "无下限" : rule.getRepayAmountFrom() + "元");
//				vo.setRepayAmountTo(null == rule.getRepayAmountTo() ? "无上限" : rule.getRepayAmountTo() + "元");
//				vo.setInvestAmountFrom(null == rule.getInvestAmountFrom() ? "无下限" : rule.getInvestAmountFrom() + "元");
//				vo.setInvestAmountTo(null == rule.getInvestAmountTo() ? "无上限" : rule.getInvestAmountTo() + "元");
                vo.setLoanTimeFrom(null == rule.getLoanTimeFrom() ? "无下限" : rule.getLoanTimeFrom() + "次");
                vo.setLoanTimeTo(null == rule.getLoanTimeTo() ? "无上限" : rule.getLoanTimeTo() + "次");
                if (null != rule.getSignType()) {
                    vo.setSignTypeName(SignActivityType.getTextByValue(rule.getSignType()).getText());
                }
                vo.setSignDays(null == rule.getSignDays() ? "空" : rule.getSignDays() + "天");


                voList.add(vo);
            }
        }

        return voList;
    }
    @Override
    public Result updateActivity(Activity activity) {
        Result result = new Result();
        result.setCode(Constant.SUCCESS);
        boolean flag = false;
        ActivityInfoVo vo = activityMapper.getActivityById(activity.getId());
        if (vo.getTickets() != null && vo.getTickets().size() != 0) {
            for (LotteryTicket ticket : vo.getTickets()) {
                if (ticket.getType() == LotteryTicketType.CASH_PACKAGE.getValue()) {
                    flag = true;
                }
            }
        }
        if(activity.getRewardPoint() == 40 && activity.getStatus() == 1){//添加秒借邀请活动
            Map<String , Object> map = activityMapper.getMiaoJieInvestInfo();
            if(map != null && map.size() != 0){
                logger.info("当前已存在有效的秒借进行中邀请活动");
                throw new ServiceException("当前已存在有效的秒借进行中邀请活动");
            }
        }
        if ((activity.getRewardPoint() == RewardPointType.REGISTER.getValue()
                || activity.getRewardPoint() == RewardPointType.REAL_NAME_AUTH.getValue()
                || activity.getRewardPoint() == RewardPointType.FIRST_RECHARGE.getValue()
                || activity.getRewardPoint() == RewardPointType.FIRST_INVEST.getValue()
                || activity.getRewardPoint() == RewardPointType.FIRST_INVEST_24_HOURSE.getValue()
                || activity.getRewardPoint() == RewardPointType.invitation.getValue() || (activity.getRewardPoint() == RewardPointType.invest_send_hb
                .getValue() && flag)) && activity.getStatus() == 1) {
            Map paramMap = new HashMap();
            paramMap.put("notThisId", activity.getId());
            paramMap.put("rewardPoint", activity.getRewardPoint());
            if (activity.getPublishPlatforms() != null) {
                paramMap.put("publishPlatforms", activity.getPublishPlatforms());
            }
            paramMap.put("status", activity.getStatus());
            paramMap.put("registerStartForX", activity.getRegisterStart());
            paramMap.put("registerEndForX", activity.getRegisterEnd());
            List<Activity> activityInfoVos = activityMapper.queryActivitys(paramMap);
            if (flag) {
                for (Activity activity_ : activityInfoVos) {
                    for (LotteryTicket ticket : activity_.getTickets()) {
                        if (ticket.getType() == LotteryTicketType.CASH_PACKAGE.getValue()) {
                            throw new ServiceException("您当前建立的活动与ID为" + activity.getId() + "的活动发生冲突，请修改后保存！");
                        }
                    }
                }
            } else {
                if (activityInfoVos != null && activityInfoVos.size() > 0) {
                    throw new ServiceException("您当前建立的活动与ID为" + activityInfoVos.get(0).getId() + "的活动发生冲突，请修改后保存！");
                }
            }
        }
        if (activity.getRewardPoint() == RewardPointType.LUCK_DRAW.getValue()
                || activity.getRewardPoint() == RewardPointType.MJ_TURN_TABLE.getValue()) {
            Map paramMap = new HashMap();
            if (ActivityStatus.BECOME_EFFECTIVE.getStatusValue() == activity.getStatus()) {
                paramMap.put("notThisId", activity.getId());
                paramMap.put("status", activity.getStatus());
                paramMap.put("registerStartForX", activity.getRegisterStart());
                paramMap.put("registerEndForX", activity.getRegisterEnd());
                paramMap.put("rewardPoint", activity.getRewardPoint());
                String[] publishPlatforms = activity.getPublishPlatforms().split(",");
                for (String publishPlatform : publishPlatforms) {
                    if (activity.getRewardPoint() != RewardPointType.invitation.getValue()) {
                        paramMap.put("publishPlatforms", publishPlatform);
                    }
                    List<Activity> activityInfoVos = activityMapper.queryActivitys(paramMap);
                    if (activityInfoVos != null && activityInfoVos.size() > 0) {
                        result.setCode(Constant.FAIL);
                        result.setMsg("您当前建立的活动与ID为" + activityInfoVos.get(0).getId() + "的活动发生冲突，请修改后保存！");
                        return result;
                    }
                }
            }
//            paramMap.clear();
//            paramMap.put("type", 0);
//            paramMap.put("foreignId", activity.getId());
//            Integer count = userConfigManager.queryUserConfigByCon(paramMap);
//            if (count > 0) {
//                if (activity.getStatus() == ActivityStatus.BECOME_EFFECTIVE.getStatusValue()) {
//                    paramMap.put("status", 1);
//                } else {
//                    paramMap.put("status", 0);
//                }
//                Integer ups = userConfigManager.updateStatusByCon(paramMap);
//            }

        }
        if (activityMapper.updateActivity(activity) == 1) {
            result.setCode(Constant.SUCCESS);
            result.setMsg("修改活动成功！");
            return result;
        } else {
            result.setCode(Constant.FAIL);
            result.setMsg("未更新到数据！");
            return result;
        }
    }
    @Override
    public List<ComboboxDataVO> queryInvestPeriodsComboxData(long activityId) {
        return activityMapper.queryInvestPeriodsComboxData(activityId);
    }

    @Override
    public List<Map<String, Object>> queryInvestTicketsSendInfo(long activityId) {
        return activityMapper.queryInvestTicketsSendInfo(activityId);
    }

    @Override
    public Map<String, Object> queryInvestInfo(long activityId) {
        return activityMapper.queryInvestInfo(activityId);
    }

    @Override
    public Map<String, Object> queryActTotalInvestAmount(Long activityId) {
        return activityMapper.queryActTotalInvestAmount(activityId);
    }

    @Override
    public List<InvestActStasticsInfoVo> queryInvestStatisticsInfoByCondition(Map<String, Object> condition) {
        return activityMapper.queryInvestStatisticsInfoByCondition(condition);
    }

    @Override
    public List<PackageInvestTotalAmount> queryPackageTotalInvestAmount(Map<String, Object> condition){
        return  activityMapper.queryPackageTotalInvestAmount(condition);
    }

    @Override
    public Integer queryInvestStatisticsInfoCountByCondition(Map<String, Object> condition) {
        return activityMapper.queryInvestStatisticsInfoCountByCondition(condition);
    }
}
